import * as THREE from '../../../../modules/three/three.module.js'
import {DRACOLoader} from "../../../../modules/three/jsm/loaders/DRACOLoader.js"
import {assets3dBaseUrl, DRACO_DECODER_PATH} from "../CommonConsts.js"
import {GLTFLoader} from "../../../../modules/three/jsm/loaders/GLTFLoader.js"

const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath( DRACO_DECODER_PATH )
const gltfLoader = new GLTFLoader()
gltfLoader.setDRACOLoader(dracoLoader)

// 无人机模型网格
export default class DroneMesh extends THREE.Group {

  _paddles = []
  _paSpeed = Math.PI / 5

  constructor() {
    super()
  }

  async init() {
    let drone = await gltfLoader.loadAsync( assets3dBaseUrl + 'glb/JISHEN.glb') // JISHEN jishen0523
    drone = drone.scene;
    let paddle1 = await gltfLoader.loadAsync( assets3dBaseUrl + 'glb/JIYI.glb')
    paddle1 = paddle1.scene
    this.add(drone);

    // const pos1 = box1.getCenter(new THREE.Vector3()).negate();
    // let matMove = new THREE.Matrix4().makeTranslation(pos1.x, pos1.y, pos1.z);
    // drone.traverse(object3d => {
    //   if (object3d.geometry) {
    //     const mat = matMove.clone().multiply(object3d.matrixWorld);
    //     object3d.geometry.applyMatrix4(mat);
    //   }
    // });
    drone.rotation.set(Math.PI * 0.5, 0, 0);
    drone.scale.set(20, 20, 20);
    const box1 = new THREE.Box3().setFromObject(drone);
    const droneSize = box1.getSize(new THREE.Vector3());
    drone.position.z = -0.5 * droneSize.z;

    const box2 = new THREE.Box3().setFromObject(paddle1);
    const pos2 = box2.getCenter(new THREE.Vector3()).negate();
    const matPreRotate = new THREE.Matrix4().makeRotationX(Math.PI);
    const matPreScale = new THREE.Matrix4().makeScale(0.1, 0.1, 0.1);
    const matMove = new THREE.Matrix4().makeTranslation(pos2.x, pos2.y, pos2.z);
    matMove.premultiply(matPreScale).premultiply(matPreRotate);
    //
    paddle1.traverse(object3d => {
      if (object3d.geometry) {
        const mat = matMove.clone().multiply(object3d.matrixWorld);
        object3d.geometry.applyMatrix4(mat);
      }
    });
    paddle1.position.set(0, 0.5, 0.188);
    const paddle2 = paddle1.clone();
    paddle2.position.set(0.349, 0.356, 0.188);
    const paddle3 = paddle1.clone();
    paddle3.position.set(0, -0.5, 0.188);
    const paddle4 = paddle1.clone();
    const paddle5 = paddle1.clone();
    const paddle6 = paddle1.clone();
    paddle4.position.set(-0.349, 0.356, 0.188);
    paddle5.position.set(0.349, -0.356, 0.188);
    paddle6.position.set(-0.349, -0.356, 0.188);
    this._paddles= [paddle1, paddle2, paddle3, paddle4, paddle5, paddle6];
    this.add(...this._paddles);
  }

  rotatePaddle() {
    this._paddles.forEach(it => it.rotation.z += this._paSpeed)
  }
}
